<template>
  <div class="flexContent">
    <!-- 新增收货 -->
    <h3>收货信息</h3>
    <el-form ref="ruleForm" :disabled="detail.isDetail" :model="sform" :rules="rules" label-width="100px">
      <el-row :gutter="20">
        <el-col :span="8" :offset="0">
          <el-form-item label="供应商：" prop="supplierId">
            <el-select v-if="!detail.isDetail" v-model="sform.supplierId" clearable placeholder="请选择供应商"
              style="width: 80%" popper-class="eloption" filterable @change="supplierChange" @click.native="getSCMList">
              <el-option v-for="item in firstSupplierList" :key="item.id" :value="item.id" :label="item.name" />
            </el-select>
            <span v-if="detail.isDetail">{{
              sform.supplierName ? sform.supplierName : "-"
            }}</span>
          </el-form-item>
          <el-form-item label="来货单号：" prop="goodsNumber">
            <el-input v-clearEmoji v-if="!detail.isDetail" v-model.trim="sform.goodsNumber" placeholder="请输入来货单号"
              style="width: 80%" />
            <span v-if="detail.isDetail">{{
              sform.goodsNumber ? sform.goodsNumber : "-"
            }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="8" :offset="0">
          <el-form-item label="收货仓库：" prop="warehouseName">
            <el-input v-clearEmoji v-if="!detail.isDetail" v-model.trim="sform.warehouseName" disabled
              style="width: 80%" />
            <span v-if="detail.isDetail">{{
              sform.warehouseName ? sform.warehouseName : "-"
            }}</span>
          </el-form-item>
          <el-form-item prop="desireDate" label="起运时间：">
            <el-date-picker v-if="!detail.isDetail" v-model="sform.departureTime" key="departureTime" type="datetime"
              placeholder="" :clearable="false" value-format="yyyy-MM-dd HH:mm" format="yyyy-MM-dd HH:mm"
              style="width: 80%" />
            <span v-if="detail.isDetail">{{
              sform.departureTime ? sform.departureTime : "-" | parseTime
            }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="8" :offset="0">
          <el-form-item label="采购备注：">
            <el-input v-clearEmoji v-if="!detail.isDetail" v-model.trim="sform.buyRemake" disabled style="width: 80%" />
            <span v-if="detail.isDetail">{{
              sform.buyRemake ? sform.buyRemake : "-"
            }}</span>
          </el-form-item>
          <el-form-item prop="desireDate" label="到货时间：">
            <el-date-picker v-if="!detail.isDetail" v-model="sform.arrivalTime" type="datetime" placeholder=""
              key="arrivalTime" :clearable="false" value-format="yyyy-MM-dd HH:mm" format="yyyy-MM-dd HH:mm"
              style="width: 80%" />
            <span v-if="detail.isDetail">{{
              sform.arrivalTime ? sform.arrivalTime : "-" | parseTime
            }}</span>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="16" :offset="0">
          <el-form-item label="备注：">
            <el-input v-clearEmoji v-if="!detail.isDetail" v-model.trim="sform.remake" placeholder="最多输入50个字符"
              maxlength="50" show-word-limit style="width: 80%" />
            <span v-if="detail.isDetail">{{
              sform.remake ? sform.remake : "-"
            }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="8" :offset="0">
          <el-form-item v-show="detail.isDetail" label="收货单号：">
            <span>{{ sform.number }}</span>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <div class="add">
      <el-button class="addBtn" v-show="!detail.isDetail" @click="submitForm('ruleForm')">调订单</el-button>
    </div>
    <div class="table">
      <el-form ref="formData" :model="formData">
        <el-table border row-key="key" class="tablebox" :data="formData.tableData" :expand-row-keys="expandList"
          :default-expand-all="detail.isDetail" max-height="470"
          :tree-props="{ children: 'children', hasChildren: 'hasChildren' }" style="width: 100%" size="medium">
          <el-table-column align="center" label="序号" width="80">
            <template v-slot="{ row }">
              <span v-if="row.type === '1'">{{ row.showIndex }}</span>
            </template>
          </el-table-column>
          <el-table-column align="center" prop="name" label="商品名称"
            :min-width="elTableAdaptationWidth('name', formData.tableData)">
            <template v-slot="{ row }">
              <span v-if="row.type === '1'">{{ row.name }}</span>
              <span v-if="row.type === '2'">-</span>
            </template>
          </el-table-column>
          <el-table-column align="center" prop="firstCode" label="商品条码" width="150">
            <template v-slot="{ row }">
              <span v-if="row.type === '1'">{{ row.firstCode }}</span>
              <span v-if="row.type === '2'">-</span>
            </template>
          </el-table-column>
          <!-- <el-table-column align="center" prop="firstCode" label="商品条码" :min-width="elTableAdaptationWidth('firstCode', formData.tableData)" /> -->
          <!-- <el-table-column align="center" prop="mnemonic" :min-width="elTableAdaptationWidth('mnemonic', formData.tableData)"
            label="助记符">
            <template v-slot="{ row }">
              <span v-if="row.type === '1'">{{ row.mnemonic }}</span>
              <span v-if="row.type === '2'">-</span>
            </template>
          </el-table-column> -->

          <el-table-column align="center" prop="buyNumber" label="采购数量" :min-width="120">
            <template v-slot="{ row }">
              <span v-if="row.type === '1'">{{ row.buyNumber }}</span>
              <span v-if="row.type === '2'">-</span>
            </template>
          </el-table-column>
          <el-table-column align="center" prop="pieceNumber" label="采购件数" :min-width="120">
            <template v-slot="{ row }">
              <span v-if="row.type === '1'">{{ row.pieceNumber }}</span>
              <span v-if="row.type === '2'">-</span>
            </template>
          </el-table-column>
          <el-table-column align="center" prop="takeCount" label="收货数量" :min-width="120">
            <template slot-scope="scope">
              <template v-if="!detail.isDetail &&
                (scope.row.type === '2' || scope.row.children.length === 0)
                ">
                <el-input v-clearEmoji ref="inputaldQty" v-model.number="scope.row.takeCount" placeholder=""
                  class="group-inp" size="small" style="width: 100%" @blur="numberChange(scope.row)" />
              </template>
              <span v-if="detail.isDetail">{{ scope.row.takeCount }}</span>
              <span v-if="!detail.isDetail &&
                scope.row.type === '1' &&
                scope.row.children.length > 0
                ">-</span>
            </template>
            <!-- <template slot-scope="scope" /> -->
          </el-table-column>
          <el-table-column align="center" prop="takePiece" label="收货件数" :min-width="120"/>
          <el-table-column align="center" prop="manufactureTime" label="生产日期" width="200">
            <template slot-scope="scope">
              <template v-if="!detail.isDetail &&
                (scope.row.type === '2' || scope.row.children.length === 0)
                ">
                <el-date-picker v-model="scope.row.manufactureTime" placeholder="" :picker-options="pickerOptionsStart"
                  :clearable="false" size="small" :key="'form' + scope.row.id" value-format="yyyy-MM-dd"
                  format="yyyy-MM-dd" style="width: 100%" @blur="selDateTimeFn(scope.row)" />
              </template>
              <span v-if="detail.isDetail">{{
                scope.row.manufactureTime | parseTime("YYYY-MM-DD")
              }}</span>
              <span v-if="!detail.isDetail &&
                  scope.row.type === '1' &&
                  scope.row.children.length > 0
                  ">-</span>
            </template>
            <!-- <template slot-scope="scope" /> -->
          </el-table-column>
          <el-table-column align="center" prop="standard" label="规格">
            <template v-slot="{ row }">
              <span v-if="row.type === '1'">{{ row.standard }}</span>
              <span v-if="row.type === '2'">-</span>
            </template>
          </el-table-column>
          <el-table-column align="center" prop="unitName" label="单位">
            <template v-slot="{ row }">
              <span v-if="row.type === '1'">{{ row.unitName }}</span>
              <span v-if="row.type === '2'">-</span>
            </template>
          </el-table-column>
          <el-table-column align="center" prop="producer" label="产地">
            <template v-slot="{ row }">
              <span v-if="row.type === '1'">{{ row.producer }}</span>
              <span v-if="row.type === '2'">-</span>
            </template>
          </el-table-column>
          <el-table-column align="center" prop="bigPacking" label="大包装">
            <template v-slot="{ row }">
              <span v-if="row.type === '1'">{{ row.bigPacking }}</span>
              <span v-if="row.type === '2'">-</span>
            </template>
          </el-table-column>
          <el-table-column v-if="!detail.isDetail" align="center" fixed="right" label="操作" width="150">
            <template slot-scope="scope">
              <el-button type="text" style="color: red" v-if="scope.row.type === '1' && scope.row.children.length === 0
                " @click="delRegionByIndex(scope.row.id)">删除</el-button>
              <el-button type="text" style="color: rgb(0, 132, 255)" @click="inBatchesFn(scope.row)"
                v-if="scope.row.type === '1'" :disabled="scope.row.children.length > 0">拆批</el-button>
              <!-- 添加 -->
              <i class="el-icon-plus" style="margin-right: 10px; cursor: pointer"
                v-if="scope.row.type === '2' && scope.row.lengthFlag" @click.stop="addSiblingFn(scope.row)"></i>
              <!-- 删除 -->
              <i class="el-icon-delete" v-if="scope.row.type === '2'" style="cursor: pointer"
                @click.stop="delChild(scope.row, scope.$index)"></i>
            </template>
          </el-table-column>
        </el-table>
      </el-form>
    </div>
    <div class="returnBtn">
      <el-button class="celBtn" v-if="!detail.isDetail" @click="cancelBtn">取消</el-button>
      <el-button class="celBtn" v-if="detail.isDetail" @click="cancelBtn">返回</el-button>
      <el-button class="addBtn" v-if="!detail.isDetail" @click="submitData('formData')">确定</el-button>
    </div>
    <el-dialog title="调订单" :visible.sync="dialogTableVisible">
      <h3>调订单</h3>
      <el-table border @current-change="showRow" highlight-current-row :data="gridData1" class="tablebox" height="202px"
        size="medium">
        <el-table-column label="序号" width="80" align="center">
          <template scope="scope">
            <el-radio v-model="radio" class="radio" :label="scope.$index"><span @click.native.stop>{{ scope.$index + 1
            }}</span></el-radio>
          </template>
        </el-table-column>
        <el-table-column property="number" align="center" label="订单编号" />
        <el-table-column property="createName" align="center" label="采购员" />
        <el-table-column property="warehouseName" align="center" label="收货仓库" />
        <el-table-column property="createTime" align="center" label="采购时间">
          <template v-slot="{ row }">
            <span>{{ row.createTime | parseTime("YYYY-MM-DD") }}</span>
          </template>
        </el-table-column>
      </el-table>
      <h3 style="padding-top: 30px">订单明细</h3>
      <el-table border :data="gridData2" class="tablebox" height="202px" size="medium">
        <el-table-column type="index" align="center" label="序号" width="80" />
        <el-table-column property="name" align="center" label="商品名称"
          :min-width="elTableAdaptationWidth('name', gridData2)" />
        <el-table-column property="firstCode" align="center" label="商品条码"
          :min-width="elTableAdaptationWidth('firstCode', gridData2)" />
        <el-table-column property="standard" align="center" label="规格" />
        <el-table-column property="unitName" align="center" label="单位" />
        <el-table-column property="producer" align="center" label="产地" />
        <el-table-column property="buyNumber" align="center" label="采购数量" />
        <el-table-column property="pieceNumber" align="center" label="采购件数" />
        <!-- <el-table-column property="brand" align="center" label="品牌" /> -->
      </el-table>
      <div slot="footer">
        <el-button class="celBtn" @click="cancelFn">取消</el-button>
        <el-button class="addBtn" @click="confirmFn">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { nanoid } from "nanoid";
import {
  getOrderListBySupplier,
  getOrderDetailById,
  addReceivingOrderList,
  getReceivingOrderDetail,
} from "@/api/warehouse";
import { DecimalUtils } from "@/utils/math";
import { getSCMList } from "@/api/scm";
export default {
  name: "ReceivingAdd",
  data() {
    return {
      dialogTableVisible: false,
      firstSupplierList: [],
      selectedTableColum: {},
      sign: 0,
      sform: {
        supplierId: "",
        supplierName: "",
        goodsNumber: "", // 来货单号
        departureTime: "", // 起运时间
        arrivalTime: "", // 到货时间
        remake: "", // 备注
        warehouseName: "",
        buyRemake: "",
        warehouseId: "",
        detailsList: [],
        buyOrderId: "",
        // buyDetailsId: "",
        number: "",
      },
      rules: {
        supplierId: [
          { required: true, message: "请选择供应商", trigger: "change" },
        ],
        // warehouseName: [
        //   { required: true, message: '请检查收货仓库信息', trigger: 'blur' }
        // ],
        goodsNumber: [
          {
            min: 0,
            max: 20,
            message: "长度在 0 到 20 个字符",
            trigger: "change",
          },
          {
            pattern: /^[\u4e00-\u9fa5_a-zA-Z0-9]+$/,
            message: "支持中英文数字组合",
            trigger: "change",
          },
        ],
      },
      formData: {
        buyRemake: "",
        warehouseName: "",
        warehouseId: "",
        tableData: [],
      },
      gridData1: [],
      gridData2: [],
      selected: {},
      radio: "",
      expandList: [],
      multipleSelection: [],
      pickerOptionsStart: {
        // 时间不能大于当前时间
        disabledDate: (time) => {
          return time.getTime() > Date.now();
        },
      },
      detail: {
        isDetail: false,
        id: "",
      },
    };
  },
  // watch: {
  //   formData: {
  //     immediate: true,
  //     deep: true,
  //     handler(val) {
  //       val.
  //     },
  //   },
  // },
  created() {
    // this.getSCMList();
    this.detail.id = this.$route.query.id;
    this.detail.isDetail = !!this.$route.query.id;
    if (this.detail.isDetail) {
      // 获取详情
      this.getOrderDetailById();
    }
    if (!this.detail.isDetail) {
      // 获取详情
      this.getSCMList();
    }
  },
  methods: {
    async getSCMList() {
      const res = await getSCMList();
      if (res.code === 200) {
        const data = res.data;
        this.firstSupplierList = data.list;
      }
    },
    async getOrderDetailById() {
      const res = await getReceivingOrderDetail({ id: this.detail.id });
      if (res.code === 200) {
        console.log(res.data);
        let originArr = res.data.detailsList;
        this.sform.supplierId = res.data.supplierId;
        this.sform.supplierName = res.data.supplierName;
        this.sform.goodsNumber = res.data.goodsNumber;
        this.sform.departureTime = res.data.departureTime;
        this.sform.arrivalTime = res.data.arrivalTime;
        this.sform.remake = res.data.remake;
        this.sform.buyRemake = res.data.buyRemake;
        this.sform.warehouseName = res.data.warehouseName;
        this.sform.number = res.data.number;
        let arr = [];
        originArr.forEach((item, index) => {
          let insIndex = arr.findIndex(
            (ins) => ins.firstCode === item.firstCode
          );
          if (insIndex === -1) {
            arr.push({
              ...item,
              type: "1",
              showIndex: arr.length + 1,
              key: nanoid(),
              hasChildre: false,
            });
          } else {
            arr[insIndex].hasChildre = true;
            arr[insIndex].takeCount = "-";
            arr[insIndex].takePiece = "-";
            arr[insIndex].manufactureTime = "-";
            arr[insIndex].children = [];
          }
        });
        arr.forEach((item) => {
          if (item.hasChildre) {
            item.children = originArr.filter((it) => {
              it.type = "2";
              it.key = nanoid();
              return it.firstCode === item.firstCode;
            });
          }
        });
        this.formData.tableData = arr;
      }
    },
    submitForm(formName) {
      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          this.selected = {};
          this.radio = "";
          const res = await getOrderListBySupplier({
            supplierId: this.sform.supplierId,
          });
          if (res.code === 200) {
            this.gridData1 = res.data;
            console.log(this.gridData1, "gridData");
          }
          this.dialogTableVisible = true;
        } else {
          return false;
        }
      });
    },
    submitData(formName) {
      this.dateChange();
      console.log(this.sign, "flag");

      if (this.sign === this.formData.tableData.length) {
        console.log("可以提交");
        // return;
        this.$refs.ruleForm.validate(async (valid) => {
          if (valid) {
            if (this.formData.tableData.length <= 0)
              return this.$message.warning("请先选择订单");
            // this.$refs.formData.validate(async (valid) => {
            //   if (valid) {
            console.log(this.formData, "formData");
            this.sform.detailsList = [];
            this.formData.tableData.forEach((item) => {
              if (item.children.length === 0) {
                this.sform.detailsList.push({
                  buyDetailsId: item.id,
                  takeCount: item.takeCount,
                  manufactureTime: item.manufactureTime,
                });
              } else {
                item.children.forEach((item2) => {
                  this.sform.detailsList.push({
                    buyDetailsId: item2.id,
                    takeCount: item2.takeCount,
                    manufactureTime: item2.manufactureTime,
                  });
                });
              }
            });
            console.log(this.sform, "this.sform");
            const res = await addReceivingOrderList({ ...this.sform });
            if (res.code === 200) {
              this.$message.success("添加成功");
              this.closeTag("receiving");
            } else {
              // this.$message.error(res.message);
            }
            // }/
            // });
          }
        });
      } else {
        console.log("错误");
      }
    },
    delRegionByIndex(id) {
      console.log("22222", id);
      const index = this.formData.tableData.findIndex((item) => item.id == id);
      console.log(index, "index copy.vue");
      this.formData.tableData.splice(index, 1);
      this.selected = {};
      this.radio = "";
      this.formData.tableData.forEach((item, index) => {
        item.showIndex = index + 1;
      });
      //  this.formData
    },
    // 拆批
    inBatchesFn(row) {
      // const flag = this.dateChange();
      // if (flag) {
      // console.log(index, id, "打印");
      console.log(row, "拆");
      this.selectedTableColum = {};
      this.selectedTableColum = row;
      this.expandList = [row.key];
      if (this.selectedTableColum.takeCount < 2)
        return this.$message.warning("采购数量低于两个，无法拆批");
      const val = this.selectedTableColum.takeCount - 1;
      let arr = [
        {
          key: nanoid(),
          id: this.selectedTableColum.id,
          branchName: "",
          showInput: true,
          type: "2",
          takeCount: val,
          takePiece: DecimalUtils.subNumber(
            val / this.selectedTableColum.bigPacking,
            2
          ),
          bigPacking: this.selectedTableColum.bigPacking,
          manufactureTime: null,
          lengthFlag: false,
        },
        {
          key: nanoid(),
          id: this.selectedTableColum.id,
          branchName: "",
          showInput: true,
          type: "2",
          takeCount: 1,
          takePiece: DecimalUtils.subNumber(
            1 / this.selectedTableColum.bigPacking,
            2
          ),
          bigPacking: this.selectedTableColum.bigPacking,
          manufactureTime: null,
          lengthFlag: true,
        },
      ];
      this.$set(this.selectedTableColum, "children", arr);
      arr = [];
      console.log(this.selectedTableColum, "selectedTableColum");
      // }
    },
    // 添加同级
    addSiblingFn(row) {
      // const flag = this.dateChange();
      // if (flag) {
      const arr = this.formData.tableData.filter((item) => {
        return item.type === "1" && item.id === row.id;
      });
      console.log(arr, "筛选出来的父级");
      let sum = 0;
      arr[0].children.forEach((item) => {
        sum += item.takeCount;
      });
      if (arr[0].buyNumber <= sum) {
        return this.$message.warning("收获件数总和不允许超过采购数量");
      } else {
        const j = arr[0].buyNumber - sum;
        this.selectedTableColum = arr[0];
        this.selectedTableColum.children.forEach((item) => {
          item.lengthFlag = false;
        });
        this.selectedTableColum.children.push({
          key: nanoid(),
          id: this.selectedTableColum.id,
          branchName: "",
          showInput: true,
          type: "2",
          takeCount: j,
          takePiece: DecimalUtils.subNumber(
            j / this.selectedTableColum.bigPacking,
            2
          ),
          bigPacking: this.selectedTableColum.bigPacking,
          manufactureTime: null,
          lengthFlag: true,
        });
      }
      // }
      // this.$set(this.selectedTableColum, "children", arr);
    },
    // 删除子级
    delChild(row, index) {
      // console.log(row, index);
      const that = this;
      const key = row.key;
      that.formData.tableData.map((item) => {
        if (item.children !== undefined) {
          for (let i = 0; i < item.children.length; i++) {
            if (item.children[i].key === key && item.children.length === 2) {
              item.children = [];
            } else if (item.children[i].key === key) {
              item.children = item.children.filter((items, index) => {
                items.lengthFlag = false;
                return items.key !== key;
              });
              item.children[item.children.length - 1].lengthFlag = true;
            }
          }
        }
      });
      return that.formData.tableData;
    },
    // 添加选中项到页面渲染表格
    confirmFn() {
      if (this.formData.tableData.length > 0) {
        this.$message.success("已切换订单");
      }
      this.formData.tableData = [];
      this.gridData2.forEach((item, index) => {
        this.formData.tableData.push({
          ...item,
          takeCount: item.buyNumber,
          children: [],
          key: nanoid(),
          type: "1",
          showIndex: index + 1,
          takePiece: DecimalUtils.subNumber(
            item.buyNumber / item.bigPacking,
            2
          ),
        });
      });
      // console.log(this.formData.tableData, 'this.formData.tableData')
      // console.log(this.formData)
      this.sform.buyRemake = this.formData.buyRemake;
      this.sform.warehouseName = this.formData.warehouseName;
      this.sform.warehouseId = this.formData.warehouseId;
      this.gridData2 = [];
      this.dialogTableVisible = false;
    },
    cancelFn() {
      this.dialogTableVisible = false;
      this.selected = {};
      this.radio = "";
    },
    async showRow(row) {
      // 赋值给radio
      if (row) {

        this.radio = this.gridData1.indexOf(row);
        this.selected = row;
        console.log(this.selected);
        this.sform.buyOrderId = row.id;
        const res = await getOrderDetailById({ id: row.id });
        if (res.code === 200) {
          this.gridData2 = res.data.detailsList;
          this.formData.buyRemake = res.data.remake;
          this.formData.warehouseName = res.data.warehouseName;
          this.formData.warehouseId = res.data.warehouseId;
        }
        console.log(res.data, "详情");
      }
    },
    supplierChange() {
      this.gridData2 = [];
      this.formData.tableData = [];
      this.formData.buyRemake = "";
      this.formData.warehouseName = "";
      this.sform.buyRemake = "";
      this.sform.warehouseName = "";
      this.formData.warehouseId = "";
      this.sform.warehouseId = "";
      this.selected = {};
      this.radio = "";
    },
    numberChange(obj) {
      // console.log(row, "row");
      // console.log(obj.key, "key");
      if (obj.type === "1" && obj.takeCount !== "-") {
        console.log(this.formData.tableData, " this.formData.tableData");
        const index = this.formData.tableData.findIndex(
          (item) => item.id == obj.id
        );
        const row = this.formData.tableData[index];
        const takeCount = row.takeCount;
        const buyNumber = row.buyNumber;
        // 判断收获件数不能大于采购数量
        if (takeCount > buyNumber) {
          this.$message.warning("收获数量不能大于采购数量");
          console.log("输入的收获数量大于采购数量");
          // row.takeCount = 1
          this.$set(this.formData.tableData[index], "takeCount", buyNumber);
        }
        // 非空判断
        const isPositiveInteger = /^[1-9]\d*$/.test(takeCount);
        if (!isPositiveInteger) {
          this.$message.warning("收获数量必须为正整数");
          this.$set(this.formData.tableData[index], "takeCount", buyNumber);
        }
        if (!takeCount) {
          this.$message.warning("收获数量不能为空");
          this.$set(this.formData.tableData[index], "takeCount", buyNumber);
        }
        // 计算收货件数
        // row.takePiece = (row.takeCount / row.bigPacking).toFixed(2)
        this.$set(
          this.formData.tableData[index],
          "takePiece",
          DecimalUtils.subNumber(row.takeCount / row.bigPacking, 2)
        );
      } else if (obj.type === "2") {
        const index2 = this.formData.tableData.findIndex(
          (item) => item.id == obj.id
        );
        // 求和
        console.log(this.formData.tableData[index2].children);
        let sum = 0;
        let sum1 = 0;
        this.formData.tableData[index2].children.forEach((item) => {
          sum += item.takeCount;
          if (item.key !== obj.key) {
            sum1 += item.takeCount;
          }
        });
        const numMax = this.formData.tableData[index2].buyNumber - sum1;
        console.log(sum, " sum 222");
        this.formData.tableData[index2].children.forEach((item3, index3) => {
          if (item3.key === obj.key) {
            // 1. 总和不超过采购数量
            console.log(this.formData.tableData[index2].buyNumber, sum, "sum");
            if (sum > this.formData.tableData[index2].buyNumber) {
              this.$set(
                this.formData.tableData[index2].children[index3],
                "takeCount",
                numMax
              );
              this.$message.warning("总收获数量不能大于采购数量");
            }
            // 2. 非空判断
            if (!item3.takeCount) {
              this.$message.warning("收获数量不能为空");
              this.$set(
                this.formData.tableData[index2].children[index3],
                "takeCount",
                numMax
              );
            }
            // 3. 正则校验
            const isPositiveInteger = /^[0-9]\d*$/.test(item3.takeCount);
            if (!isPositiveInteger) {
              this.$message.warning("收获数量必须为正整数");
              this.$set(
                this.formData.tableData[index2].children[index3],
                "takeCount",
                numMax
              );
            }

            // 计算收获件数
            this.$set(
              this.formData.tableData[index2].children[index3],
              "takePiece",
              DecimalUtils.subNumber(item3.takeCount / item3.bigPacking, 2)
            );
          }
        });
      }
    },
    cancelBtn() {
      this.closeTag("receiving");
    },
    // 判断生产日期非空
    dateChange() {
      this.sign = 0;
      for (let i = 0; i < this.formData.tableData.length; i++) {
        let item = this.formData.tableData[i];
        let index = i;
        if (item.children.length > 0) {
          const flag = item.children.every((item2) => {
            return item2.manufactureTime;
          });
          if (flag) {
            this.sign += 1;
          } else {
            this.$message.warning(
              "请检查第" + item.showIndex + "条数据中的生产日期"
            );
            break;
          }
        } else {
          if (!item.manufactureTime) {
            this.$message.warning("第" + item.showIndex + "条生产日期为空");
            break;
          } else {
            this.sign += 1;
          }
        }
      }
      // this.formData.tableData.forEach((item, index) => {
      // });
    },
    // 判断日期重复
    selDateTimeFn(row) {
      if (row.type === "1") {
        return;
      } else if (row.type === "2" && row.manufactureTime) {
        const index = this.formData.tableData.findIndex(
          (item) => item.id == row.id
        );
        const index2 = this.formData.tableData[index].children.findIndex(
          (item) => item.key == row.key
        );
        const arr = this.formData.tableData[index].children.map((item) => {
          return item.manufactureTime;
        });
        let count = 0;
        this.formData.tableData[index].children.forEach((item) => {
          if (item.manufactureTime) {
            count += 1;
          }
        });
        let arr1 = [...new Set(arr)].filter((item) => {
          return item;
        });

        // console.log(arr1, "arr1");
        if (arr1.length < count) {
          console.log("有重复");
          this.$message.warning("同一种商品生产日期不能重复");
          this.$set(
            this.formData.tableData[index].children[index2],
            "manufactureTime",
            ""
          );
        } else {
          console.log("没有重复");
        }
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.flexContent {
  h3 {
    margin: 0;
    margin-bottom: 10px;
  }
}
</style>
